<?php
namespace Duobao\Model;

use Think\Model;
use Duobao\Controller\LogController as MyLog;

class WeixinModel extends Model{

    protected $tableName = 'user';
    /**
     * @param $obj
     *
     * @return bool 判断用户是否已经关注了，如果已经关注了什么都不干，否则进入插入用户
     */
    public function existUser($obj){
        #MyLog::write('判断用户是否存在');
        #转换json
        #首先查找openid在数据库是否已经存在
        $condition['openid'] = $obj['openid'];
        $model = new \Think\Model();
        $result = $model->table("__OPENID__")->where($condition)->find();
        #存在
        if($result){
            #更新用户的关注时间
            $data['updatetime'] = date('Y-m-d H:i:s',time());
            $model->table('__OPENID__')->where($condition)->save($data);
            return true;
        }else{
            #用户的openid在openid表中不存在，兼容性的考虑，兼容以前没有使用openid表的情况，判断用户在user表中是否存在
            #如果存在于user表中，将用户的openid添加一天记录到openid表中
            $where['union_id'] = $obj['unionid'];
            $userExist = $model->table('__USER__')->where($where)->find();
            if($userExist){
                #MyLog::write('进入判断userexist');
                return $this->addOpenId($obj);
            }else{
                #新用户，调用插入函数
                return $this->insertUser($obj);
            }
        }
    }

    /**
     * 判断用户是否已经关注公众号，version 2
     */
    public function existUser2($obj){
        #直接判断openid表中的用户是否存在
        #MyLog::write('进入existUser2');
        $condition['openid'] = $obj['openid'];
        $model = new \Think\Model();
        $exist = $model->table("__OPENID__")->where($condition)->find();
        if($exist){
            #更新用户的关注时间
            $data['updatetime'] = date('Y-m-d H:i:s',time());
            $model->table('__OPENID__')->where($condition)->save($data);
            return true;
        }else{
            #用户的openid在openid表中不存在，兼容性的考虑，兼容以前没有使用openid表的情况，判断用户在user表中是否存在
            #如果存在于user表中，将用户的openid添加一天记录到openid表中
            $where['union_id'] = $obj['unionid'];
            $userExist = $model->table('__USER__')->where($where)->find();
            if($userExist){
                #MyLog::write('进入判断userexist');
                return $this->addOpenId($obj);
            }else{
                #新用户，调用插入函数
                return $this->insertUser($obj);
            }
        }
    }

    /**
     * @param $obj 微信关注事件json_decode后的用户数据数组
     */
    private function insertUser($obj){
        $model = new \Think\Model();
        $rand_name = "夺宝小兵".rand(111,99999);

        #判断微信返回的用户昵称是否存在，如果存在直接插入数据，如果不存在，给定默认值
        if(array_key_exists('nickname',$obj)) {
            $user['state'] = $obj['subscribe'];#用户关注状态
            $user['openid'] = $obj['openid'];#用户openid
            $user['nickname'] = $obj['nickname'];#昵称
            $user['logo'] = $obj['headimgurl'];#用户图像
            $user['addtime'] = date("Y-m-d H:i:s", $obj['subscribe_time']);#用户的关注时间
            $user['updatetime'] = $obj['subscribe_time'];#关注更新时间
            $user['sex'] = $obj['sex'];#用户性别1：表示男，0：表示女
            $user['language'] = $obj['language'];#用户语言
            $user['city'] = $obj['city'];#用户城市
            $user['province'] = $obj['province'];#用户省份
            $user['country'] = $obj['country'];#用户的国家
            $user['union_id'] = $obj['unionid'];#用户unionid
            $rand_name = $obj['nickname'];
        }else{
            $user['state'] = 0;#用户关注状态
            $user['openid'] = $obj['openid'];#用户openid
            $user['nickname'] = $rand_name;
            $user['addtime'] = date("Y-m-d H:i:s",time());
            $user['updatetime'] = time();
            $user['sex'] = 1;
            $user['union_id'] = $obj['unionid'];#用户unionid
        }
        #user表中添加
        $result1 = $this->add($user);

        $member['username'] = $rand_name;
        $member['img'] = $obj['headimgurl'];
        $member['time'] = $obj['subscribe_time'];
        $member['weixin_id'] = $result1;
        #新用户关注送n个夺宝币,获取配置表中，用户关注送币的开关
        $config = $model->query("select `value` from __PREFIX__config where name IN('follow_switch','follow_money','follow_each') ORDER BY id");

//        foreach($config as $value){
//            MyLog::write($value);
//        }
        $follow_switch = $config[0]['value'];
        $follow_money =  $config[1]['value'];
        $follow_each = $config[2]['value'];
       // MyLog::write($follow_each.":".$follow_money.":".$follow_switch);
        if($follow_switch != 0 && $follow_money > 0){

            #将config表中的钱减2
            $update = $model->execute("update __PREFIX__config set `value`=`value` - $follow_each WHERE name = 'follow_money'");
            if(!$update){
                MyLog::write('新用户加钱失败');
            }else{
                $member['money'] = $follow_each;
            }
        }


        $result2 = $model->table('__MEMBER__')->add($member);

        #在openid表中插入用户openid的记录值
        $msg['uid'] = $result2;
        $msg['openid'] = $obj['openid'];
        $msg['wxhao '] = C('wx_hao');
        $msg['addtime'] = date('Y-m-d H:i:s',time());
        $msg['updatetime'] = $msg['addtime'];
        $model->table('__OPENID__')->add($msg);

        if($result2){
            #MyLog::write('插入成功');
            #将openid与partner_relationship中对应
            $condition['openid'] = $obj['openid'];
            $data['uid'] = $result2;
            $model->table('__PARTNER_RELATIONSHIP__')->where($condition)->save($data);
            return $result2;
        }else{
            MyLog::write('插入用户微信数据失败');
            return false;
        }
    }

    /**
     * 兼容函数，用户在user表中用户存在，而在openid表中不存在
     */
    public function addOpenId($obj){
       #更具unionid获取用户的uid
        $model = new \Think\Model();
        $condition['union_id'] = $obj['unionid'];
        $wx_id = $model->table("__USER__")->where($condition)->getField('id');

        if(empty($wx_id)){
            return false;
        }

        #在member中获取用户的uid
        $where['weixin_id'] = $wx_id;
        $uid = $model->table('__MEMBER__')->where($where)->getField('uid');
        #更新openid表
        $data['openid'] = $obj['openid'];
        $data['uid'] = $uid;
        $data['wxhao'] = C('wx_hao');
        $data['addtime'] = date('Y-m-d H:i:s',time());
        $data['updatetime'] =  $data['addtime'];

        $result = $model->table('__OPENID__')->add($data);
        if($result){
            #MyLog::write('返回uid');
            return $uid;#在用户登陆时需要返回用户的uid
        }else{
            MyLog::write('openid表中不存在用户的openid时插入用户的openid失败');
            return false;
        }
    }
    /*end weixin model*/
}